import { Document, Packer, HeadingLevel } from 'docx'
import { richTextToParagraph } from './html'
import { downloadFile } from '@/utils/download'
import docxDefaultConfig from '@/config/docx-default-config'
import { MineTypeEnum } from '@/constants/mine-type'
import { uploadCommon } from '@/api/common'

export function pureRichTextExportDocx(
  richText: string | string[],
  filename?: string
) {
  docxPackerToBlob(converRichTextToDocument(richText)).then((blob) => {
    const url = URL.createObjectURL(blob)
    downloadFile(url, filename ? `${filename}.docx` : undefined)
  })
}

function docxPackerToBlob(doc: Document) {
  return Packer.toBlob(doc)
}

export function pureRictTextToBlob(richText: string | string[]) {
  return docxPackerToBlob(converRichTextToDocument(richText))
}

export function converRichTextToDocument(richText: string | string[]) {
  const doc = new Document({
    features: {
      updateFields: true
    },

    sections: [
      {
        properties: {
          page: {
            // 这里因为配置已经是 mm => twip 单位所以不用在转换了
            margin: docxDefaultConfig.a4.margins,
            size: {
              width: docxDefaultConfig.a4.pageWidth,
              height: docxDefaultConfig.a4.pageHeight
            }
          }
        },
        children: richTextToParagraph(richText)
      }
    ]
  })

  return doc
}

export function getHeadingLevel(level: number) {
  return HeadingLevel['HEADING_' + level]
}

export const uploadDocx = async (
  getTemplateString?: () => any,
  filename?: string
) => {
  if (!getTemplateString) {
    return {}
  }
  const blob = await pureRictTextToBlob(getTemplateString())

  const formData = new FormData()
  formData.append(
    'file',
    new File([blob], 'xxx.docx', { type: MineTypeEnum.DOCX })
  )
  const { data = {} } = await uploadCommon(formData)

  return {
    // ...data,
    // name: filename ? `${filename}.docx` : data.name,
    fileData: filename ? `${filename}.docx` : data.name,
    filePath: data.url
  }
}

export * from './docx'
